/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.manager;

import com.ez2find.model.Area;
import com.ez2find.model.Job;
import com.ez2find.model.JobCategorie;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Site;
import java.io.IOException;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Owner
 */
@Stateless
public class JobManagerBean implements JobManagerLocal {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Job job)throws Exception {
        em.persist(job);
    }
 
    public void update(Job job)throws Exception {
        em.merge(job);
    }
    
    public Job merge(Job job)throws Exception {
        return em.merge(job);
    }
    
    public void delete(Job job)throws Exception {
        job=em.merge(job);
        em.remove(job);
    }
    
    public Job find(long id){
        return em.find(Job.class,id);
    }

    public List<Job> listAll(){
        Query query=em.createNamedQuery("listAllJobs");
        List<Job> result=query.getResultList();
        return result;
    }
    
    public long lastCode(){
        try{
            Query query=em.createNamedQuery("lastJobCode");
            return (Long) query.getSingleResult();
        }catch(Exception ex){
            return 0;
        }
    }
    
    public List<Job> listJobsSite(Site site, boolean jobC, JobCategorie jobCategorie, String consult){
        Query query=em.createQuery("SELECT j FROM Job j WHERE j.site=:site AND j.status='active'"+consult+" ORDER BY j.publishDate DESC, j.code DESC");
        query.setParameter("site", site);
        if(jobC)
            query.setParameter("jobCategorie", jobCategorie);
        List<Job> result=query.getResultList();
        return result;
    }
    
    public List<Job> listJobsArea(Area area, boolean jobC, JobCategorie jobCategorie, String consult){
        Query query=em.createQuery("SELECT j FROM Job j WHERE j.area=:area AND j.status='active'"+consult+" ORDER BY j.publishDate DESC, j.code DESC");
        query.setParameter("area", area);
        if(jobC)
            query.setParameter("jobCategorie", jobCategorie);
        List<Job> result=query.getResultList();
        return result;
    }
    
}
